import { View, Text, Switch, Button  } from "@tarojs/components";

import './inputActivity.scss'
import {  useReducer, useState } from "react";

import request from '@/utils/request.js'
import { useReady } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import Dialog from "@/component/Dialog/Dialog"
import { ActionSheet,Picker, DatePicker, Divider, Input, Space, TextArea, Uploader } from '@nutui/nutui-react-taro'
// import FormData from "@/utils/formData.js";
import { IconFont } from "@nutui/icons-react-taro";

import FormData from 'miniprogram-formdata'

definePageConfig({
    navigationBarTitleText: "发布活动"
})
export default function InputActivity() {
    useReady(() => {
        getTypeList()

    })
    const [typeList, setTypeList] = useState([])
    // const imgFormData = new FormData()

    const defaultValue = new Date()
    const defaultDescription = `${defaultValue.getFullYear()}-${defaultValue.getMonth() + 1
        }-${defaultValue.getDate()}`
    // 控制开关
    const initFlagVal = {
        actTagIsOpen: false,
        actPeoIsOpen: false,
        actTypeIsOpen: false,
        gkIsOpen: false,
        durationStartTimeIsOpen: false
    }
    //控制表单数据
    const initValue = {
        title: '狼人杀之夜',
        introduce: '这是一个以狼人杀为主题的互动游戏活动',
        imgUrls: [
            'https://hd-uat-1258162617.cos.ap-guangzhou.myqcloud.com/app/1871804987568394242/upload/677789d2e4b07c26f3174ff8.jpeg',
            'https://hd-uat-1258162617.cos.ap-guangzhou.myqcloud.com/app/1871804987568394242/upload/677789d1e4b07c26f3174ff7.jpeg'
        ],
        durationStartTime: '2025-2-10 09:00:00',
        tags: ['娱乐','社交'],
        durationEndTime: '2025-2-11 18:00:00',
        province:'广东省',
        city:'广州市',
        destName: "广州市北京路",
        destLongitude: "113.264385",
        destLatitude: "23.129112",
        minNumOfPeople: 10, // 最小人数
        isWrittenOff: 1,    // 是否允许签到
        isManualReviewed: 1,         
        typeId:1, // 活动类型id
        openness: 1, // 公开性
        participateInNotice: '加入活动后，请注意活动现场安排。',
        refundNotice: '若取消报名，请提前三天通知我们',
        showToParticipants: '所有参与者将在活动前一天收到详细信息',
        tickets:[
            {
                "ticketName": "男生票",
                "singleNum": 1,
                "quantity": 30,
                "price": 6900,
                "bookStartTime": "2024-11-01 00:00:00",
                "bookEndTime": "2024-12-09 23:59:59",
                "validStartTime": "2024-12-10 09:00:00",
                "validEndTime": "2024-12-10 18:00:00",
                "description": "专为男生设定的票种。",
                "isOnSale": 1
              },
              {
                "ticketName": "女生票",
                "singleNum": 1,
                "quantity": 30,
                "price": 3900,
                "bookStartTime": "2024-11-01 00:00:00",
                "bookEndTime": "2024-12-09 23:59:59",
                "validStartTime": "2024-12-10 09:00:00",
                "validEndTime": "2024-12-10 18:00:00",
                "description": "专为女生设定的票种。",
                "isOnSale": 1
              },
        ]
    }
    const [formDataFlag, flagDispatch] = useReducer((state, action) => {
        switch (action.type) {
            case 'actTagIsOpen':
                return { ...state, actTagIsOpen: action.payload }
            case 'actPeoIsOpen':
                return { ...state, actPeoIsOpen: action.payload }
            case 'actTypeIsOpen':
                return { ...state, actTypeIsOpen: action.payload }
            case 'gkIsOpen':
                return { ...state, gkIsOpen: action.payload }
            case 'durationStartTimeIsOpen':
                return { ...state, durationStartTimeIsOpen: action.payload }
            default:
                return state;
        }

    }, initFlagVal)
    const [formData, dispatch] = useReducer((state, action) => {
        switch (action.type) {
            case 'title':
                return { ...state, title: action.payload }
            case 'introduce':
                return { ...state, introduce: action.payload }
            case 'imgUrls':
                
                return { ...state,imgUrls: [...state.imgUrls, action.payload]}
            case 'minNumOfPeople':
                return { ...state, minNumOfPeople: action.payload }
            case 'typeId':
                return { ...state, typeId: action.payload }
            case 'isWrittenOff':
                return { ...state, isWrittenOff: action.payload.value ? 1 : 0 }
            case 'isManualReviewed':
                return { ...state, isManualReviewed: action.payload.value ? 1 : 0 }
            case 'openness':
                return { ...state, openness: action.payload }
            case 'participateInNotice':
                return { ...state, participateInNotice: action.payload }
            case 'refundNotice':
                return { ...state, refundNotice: action.payload }
            case 'showToParticipants':
                return { ...state, showToParticipants: action.payload }
            default:
                return state;
        }

    }, initValue);

    console.log(formData);
    console.log(formDataFlag);

    const formDataChange = (_value) => {

    }
    const getTypeList = () => {
        request({
            url: 'api/social/activity/typeList',
        }).then(res => {
            let arr: any[] = []
            res.data.typeList.map(item => arr.push({value: item.id, text: item.name}))
            setTypeList(arr as never[])
        })

    }

    // const onTimeChange = (e) => {
    //     console.log(e)
    // }

    const navActTemp = () => {
        Taro.navigateTo({
            url: '/activity/actCardTemp'
        })

    }


    const beforeXhrUpload=(_taroUploadFile: any, options: any)=>{
        // let params = options.taroFilePath;

        const fd = new FormData()

        // formData.appendFile("img", params);
        fd.append("img", options.params);
        // let data = formData.getData();
       
       Taro.uploadFile({
        url: 'https://uat.hd.astraia.cn/api/social/uploadImg', //仅为示例，非真实的接口地址
        filePath: options.taroFilePath,
        name: 'img',
        header:{ 
            'Authorization': Taro.getStorageSync('token'),
            // 'Content-Type': 'form-data'
         } ,
        formData:fd,
        success (res){
            
          const data = JSON.parse(res.data)
    //    const arr=   formData.imgUrls.push(data.url)
          dispatch({type: 'imgUrls', payload: data.data.url})
          //do something
        }
      })

        // const uploadTask = taroUploadFile({
        //     url: options.url,
        //     filePath: options.taroFilePath,
        //     fileType: options.fileType,
        //     header: {
        //       'Content-Type': 'multipart/form-data',
        //       ...options.headers,
        //     },
        //     formData,
        //     name: options.name,
        //     success(response: { errMsg: any; statusCode: number; data: string }) {
        //         
        //       if (options.xhrState === response.statusCode) {
        //         
        //         options.onSuccess?.(response, options)
        //       } else {
        //         
        //         options.onFailure?.(response, options)
        //       }
        //     },
        //     fail(e: any) {
        //         
        //       options.onFailure?.(e, options)
        //     },
        //   })
        //   options.onStart?.(options)
        //   uploadTask.progress(
        //     (res: {
        //       progress: any
        //       totalBytesSent: any
        //       totalBytesExpectedToSend: any
        //     }) => {
        //       options.onProgress?.(res, options)
        //     }
        //   )
    }

    return (
        <View >
            <View className="container">
                <View className="top">
                    <Input placeholder="请填写活动标题（必填）" style={{
                        // @ts-ignore
                        '--nutui-input-font-size': '28rpx',
                        '--nutui-input-color': '#2A2B30'
                    }} value={formData.title} onChange={(value) => { dispatch({ type: 'title', payload: value }) }}></Input>
                    <Divider />
                    <TextArea style={{
                        // @ts-ignore
                        '--nutui-textarea-font': '26rpx',
                        '--nutui-input-color': '#2A2B30'
                    }} value={formData.introduce} onChange={(value) => { dispatch({ type: 'introduce', payload: value }) }} placeholder="描述一下活动的亮点、活动内容..."></TextArea>
                    <View >
                        <Space wrap>
                            <Uploader
                                value={formDataFlag.imgUrls}
                                maxCount={5}
                                multiple
                                beforeXhrUpload={beforeXhrUpload}
                               
                            />
                        </Space>
                        <View className="tagList">
                            <View className="tag-item" onClick={() => { flagDispatch({ type: 'actTagIsOpen', payload: true }) }}> 添加活动标签</View>
                        </View>
                        <View style={{ display: 'flex', justifyContent: 'flex-start', color: '#2A2B30', marginTop: '40rpx' }}>
                            <View className="address">
                                <IconFont fontClassName="icon-dizhiguanli" classPrefix="iconfont" color="#2A2B30" size={14} />
                                <Text>天新娱池...</Text>
                                <IconFont fontClassName="icon-youbian-tianchong" classPrefix="iconfont" color="#2A2B30" size={14} />
                            </View>
                            <View className="address" style={{ marginLeft: '20rpx' }} onClick={() => { flagDispatch({ type: 'durationStartTimeIsOpen', payload: true }) }}>
                                <IconFont fontClassName="icon-time" classPrefix="iconfont" color="#2A2B30" size={14} />
                                <Text>07.30 周二 11:00-08.01 周四 11:00</Text>
                                <DatePicker
                                    title="开始时间"
                                    visible={formDataFlag.durationStartTimeIsOpen}
                                    pickerProps={{
                                        popupProps: { zIndex: 1220 },
                                    }}
                                    defaultValue={new Date(`${defaultDescription}`)}
                                    showChinese
                                    type="datetime"
                                    onCancel={() => flagDispatch({ type: 'durationStartTimeIsOpen', payload: false })}
                                    onConfirm={(options, values) => {
                                        //   setShow1(false)
                                        //   confirm(values, options)
                                        console.log('onconfirm')
                                    }}
                                />
                                <IconFont fontClassName="icon-youbian-tianchong" classPrefix="iconfont" color="#2A2B30" size={14} />
                            </View>
                        </View>
                    </View>
                </View>

                <View className="middle">
                    <View className="middle-item" onClick={() => { flagDispatch({ type: 'actPeoIsOpen', payload: true }) }}>
                        <View className="middle-item-left">活动成行最低人数</View>
                        <View className={ formData.minNumOfPeople?'middle-item-right active':'middle-item-right '} >{formData.minNumOfPeople?formData.minNumOfPeople:<View>请选择<IconFont fontClassName="icon-right" classPrefix="iconfont" color="#C0C3CE" size={14}/></View>} </View>

                    </View>
                    <Divider />
               
                        <View className="middle-item" onClick={() => { flagDispatch({ type: 'actTypeIsOpen', payload: true }) }}>
                            <View className="middle-item-left">活动类型</View>
                            <View className={ formData.typeId?'middle-item-right active':'middle-item-right '} >{formData.minNumOfPeople?formData.minNumOfPeople:<View>请选择<IconFont fontClassName="icon-right" classPrefix="iconfont" color="#C0C3CE" size={14}/></View>} </View>
                        </View>
              
                    <Divider />
                    <View className="middle-item" onClick={()=>{ Taro.navigateTo({url:'/activity/inputTicket'})}}>
                        <View className="middle-item-left">票种设置</View>
                        <View className={ formData.minNumOfPeople?'middle-item-right active':'middle-item-right '} >{formData.minNumOfPeople?formData.minNumOfPeople:<View>待设置<IconFont fontClassName="icon-right" classPrefix="iconfont" color="#C0C3CE" size={14}/></View>} </View>
                    </View>
                    <Divider />
                    <View className="middle-item" onClick={navActTemp}>
                        <View className="middle-item-left">活动名片模板创建</View>
                        <View className={ formData.minNumOfPeople?'middle-item-right active':'middle-item-right '} >{formData.minNumOfPeople?formData.minNumOfPeople:<View>请选择<IconFont fontClassName="icon-right" classPrefix="iconfont" color="#C0C3CE" size={14}/></View>} </View>
                    </View>
                    <Divider />
                    <View className="middle-item" onClick={() => (flagDispatch({ type: 'gkIsOpen', payload: true }))}>
                        <View className="middle-item-left">公开</View>
                        <View className={ formData.openness?'middle-item-right active':'middle-item-right '} >{formData.openness?formData.openness:<View>请选择<IconFont fontClassName="icon-right" classPrefix="iconfont" color="#C0C3CE" size={14}/></View>} </View>
                    </View>
                    <Divider />
                    <View className="middle-item" onClick={()=>{ Taro.navigateTo({url:'/activity/shequn'})}}>
                        <View className="middle-item-left">关联社群</View>
                        <View className={ formData.minNumOfPeople?'middle-item-right active':'middle-item-right '} >{formData.minNumOfPeople?formData.minNumOfPeople:<View>请选择<IconFont fontClassName="icon-right" classPrefix="iconfont" color="#C0C3CE" size={14}/></View>} </View>
                    </View>
                    <Divider />
                    <View className="middle-item">
                        <View className="middle-item-left">授权场地方核销本活动</View>
                        <View className="middle-item-right"><Switch checked color="#EC6138" onChange={(event) => {

                            dispatch({ type: 'isWrittenOff', payload: event.target })
                        }} /></View>
                    </View>
                    <Divider />
                    <View className="middle-item">
                        <View className="middle-item-left">超过人数上限禁止报名</View>
                        <View className="middle-item-right"><Switch checked color="#EC6138" /></View>
                    </View>
                    <Divider />
                    <View className="middle-item">
                        <View className="middle-item-left">报名者是否需要进行人工审核</View>
                        <View className="middle-item-right"><Switch checked color="#EC6138" onChange={(event) => { dispatch({ type: 'isManualReviewed', payload: event.target }) }} /></View>
                    </View>
                </View>

                <View className="bottom">
                    <View className="bottom-item">报名须知</View>
                    <TextArea className="bottom-item text_area" style={{
                        // @ts-ignore
                        '--nutui-textarea-font': '26rpx',
                        '--nutui-input-color': '#2A2B30'
                    }} value={formData.participateInNotice} onChange={(value) => { dispatch({ type: 'participateInNotice', payload: value }) }}  ></TextArea>

                    <View className="bottom-item">退款须知</View>
                    <TextArea className="bottom-item text_area" style={{
                        // @ts-ignore
                        '--nutui-textarea-font': '26rpx',
                        '--nutui-input-color': '#2A2B30'
                    }} value={formData.refundNotice} onChange={(value) => { dispatch({ type: 'refundNotice', payload: value }) }}  ></TextArea>

                    <View className="bottom-item">参与者加入活动后，需要展示的信息</View>
                    <TextArea className="bottom-item text_area"
                        style={{
                            // @ts-ignore
                            '--nutui-textarea-font': '26rpx',
                            '--nutui-input-color': '#2A2B30'
                        }} value={formData.showToParticipants} onChange={(value) => { dispatch({ type: 'showToParticipants', payload: value }) }}
                    ></TextArea>
                    <View className="bottom-item mobile" >
                        <View>联系方式</View>
                        <View>13751815694</View>
                    </View>
                </View>


            </View>
            <View className="bottom-btn">
                <Button className="pA global_button" onClick={()=>{
                    request({url:'api/social/activity/release',method:'post',data:formData}).then(res=>{
                        Taro.navigateTo({
                            url:'/activity/releaseSuccess'
                        })
                    })
                }}>发布活动</Button>
            </View>


            <Dialog title={'活动人数'} visible={formDataFlag.actPeoIsOpen} onCancel={() => {
                flagDispatch({ type: 'actPeoIsOpen', payload: false })
            }}>
                <Input placeholder="请输入人数 例：1-3人" type="number" className="inp"
                    style={{//@ts-ignore
                        '--nutui-input-font-size': '28rpx'
                    }}
                    onChange={(value) => { dispatch({ type: 'minNumOfPeople', payload: value }) }}
                     />
            </Dialog>
            <Dialog title={'活动标签'} visible={formDataFlag.actTagIsOpen} 
            onCancel={() => {
                flagDispatch({ type: 'actTagIsOpen', payload: false })
            }}
            >
                <Input placeholder="例：桌游达人" type="number" className="inp"
                value={formData.minNumOfPeople}
                    style={{//@ts-ignore
                        '--nutui-input-font-size': '28rpx'
                    }} 
                    onChange={(value) => { dispatch({ type: 'minNumOfPeople', payload: value }) }} 
                    />
            </Dialog>

            <ActionSheet
                style={{
                    // @ts-ignore
                    '--nutui-actionsheet-item-line-height': '34px',
                    fontSize: '32rpx',
                    fontWeight: '500',

                }}
                visible={formDataFlag.gkIsOpen}
                cancelText="取消"
                options={[{
                    id: "1",
                    name: '分享可见',
                },
                {
                    id: "2",
                    name: '社群成员可见',
                },
                {
                    id: "3",
                    name: '所有人可见',
                },]}
                onSelect={(_item, index) => {
                    dispatch({ type: 'openness', payload: ++index })
                    flagDispatch({ type: 'gkIsOpen', payload: false })
                }}
                onCancel={() => flagDispatch({ type: 'gkIsOpen', payload: false })}
            />
            <Picker visible={formDataFlag.actTypeIsOpen} onConfirm={(_opt,val)=>{
                dispatch({type:'typeId',payload:val[0]})
                flagDispatch({ type: 'actTypeIsOpen', payload: false })
                }} options={typeList}   onCancel={() => flagDispatch({ type: 'actTypeIsOpen', payload: false })} className="custom-picker "/>
        </View>

    )

}


